package com.imooc.controller;

import com.alibaba.druid.util.StringUtils;
import com.imooc.error.BusinessException;
import com.imooc.error.EmBusinessError;
import com.imooc.response.CommonReturnType;
import com.imooc.service.OrderService;
import com.imooc.service.model.OrderModel;
import com.imooc.service.model.UserModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/api/order")
public class OrderController {

  @Autowired
  private OrderService orderService;

  @Autowired
  private HttpServletRequest httpServletRequest;

  @Autowired
  private RedisTemplate redisTemplate;

  //下单
  @PostMapping("/createOrder")
  public CommonReturnType createOrder(@RequestParam(name = "goodsId") Integer goodsId,
                                      @RequestParam(name = "amount") Integer amount,
                                      @RequestParam(name = "promoId", required = false) Integer promoId) throws BusinessException {
    String token = httpServletRequest.getParameterMap().get("token")[0];
    if (StringUtils.isEmpty(token)) {
      throw new BusinessException(EmBusinessError.USER_NOT_LOGIN, "用户还未登录");
    }

    UserModel userModel = (UserModel) redisTemplate.opsForValue().get(token);
    if (userModel == null) {
      throw new BusinessException(EmBusinessError.USER_NOT_LOGIN, "用户还未登录");
    }

    OrderModel orderModel = orderService.createOrder(userModel.getId(), goodsId, promoId, amount);
    return CommonReturnType.success();
  }
}
